# -*- coding: utf-8 -*-

import pygame, sys, Tile, pickle, Pic
from pygame.locals import *
from map_w import map_w

pygame.init()

SIZE = (800,600)

'''MapEditor by Karl

Första försök till en MapEditor,
funkar som den ska, men dock simpel.

Vänster-/högerklicka på en tile för att
byta typ på den, det finns nu 4 typer.

Tryck med scrollen för att slå på/av
okToPass, scrolla upp för att slå
på/av portal to (0,0)

För att spara en map tryck på s och för
att ladda in den tryck på l. Just nu kan
enbart en map sparas samtidigt.

För att testa kartan i spelet kör filen
test2.py

Updatera koden om ni vill.

Kommer: separata filer för de olika delarna, 
        en användbar sys_w
'''

class sys_w():
    '''Gör inget just nu!'''
    def __init__(self,parent):
        self.parent = parent
        self.size = 176,self.parent.size[1]-24
        self.screen = pygame.Surface(self.size)
        self.screen.fill(pygame.Color('white'))

    def loop(self):
        pass

    def __str__(self):
        return 'Sys'

class name_w():
    def __init__(self,parent):
        self.parent = parent
        self.font = pygame.font.Font(None,20)
        self.size = 176,20
        self.screen = pygame.Surface(self.size)
        self.screen.fill(pygame.Color('grey'))
        self.text = self.font.render('',1,pygame.Color('black'))

    def __str__(self):
        return 'Name'

    def loop(self):
        pass

    def update(self,text):
        self.text = self.font.render(str(text),1,pygame.Color('black'))
        self.screen.fill(pygame.Color('gray'))
        self.screen.blit(self.text,(0,0))

class info_w():
    def __init__(self,parent):
        self.parent = parent
        self.font = pygame.font.Font(None,20)
        self.size = self.parent.size[0]-180,20
        self.screen = pygame.Surface(self.size)
        self.screen.fill(pygame.Color('gray'))
        self.text = self.font.render('',1,pygame.Color('black'))
        self.time = -1
                                     
    def __str__(self):
        return 'Info'  

    def timer(self):
        if self.time == 0:
            self.update('',-1)
            self.time = -1
        elif self.time > 0:
            self.time -= 1

    def loop(self):
        pass

    def update(self,text,time):
        if self.time < 0:
            self.text = self.font.render(str(text),1,pygame.Color('black'))
            self.screen.fill(pygame.Color('gray'))
            self.screen.blit(self.text,(0,0))
            self.time = time*60

class core():
    def __init__(self):
        self.size = SIZE
        self.screen = pygame.display.set_mode(self.size)
        self.pos = (0,0)
        self.r_pos = (0,0)
        self.name = '0.map'
        self.split = (176,self.size[1]-24)
        self.btn = [False for i in range(5)]
        self.pics = ['grass.bmp','sand.bmp','water_s.bmp','water_d.bmp']
        self.nx,self.ny = self.dim = (28,26)
        self.map = dict(((x,y),Tile.Tile(Pic.Pic(self.pics[0]))) for x in range(self.nx) for y in range(self.ny)) 
        self.map_w = map_w(self)
        self.name_w = name_w(self)
        self.info_w = info_w(self)
        self.sys_w = sys_w(self)
        self.children = {self.sys_w:(0,0),self.map_w:(self.split[0]+4,0),
                         self.name_w:(0,self.split[1]+4),self.info_w:(self.split[0]+4,self.split[1]+4)}
        self.active = self.sys_w 
        self.screen.fill(pygame.Color('gray53'))
        for child in self.children.keys():
            self.screen.blit(child.screen,self.children[child])
        self.clock = pygame.time.Clock()
        pygame.display.flip()

    def get_input(self):
        self.pos = pygame.mouse.get_pos()
        self.active = None
        self.btn = [False for i in range(5)]
        for child in self.children:
            self.screen.blit(child.screen,self.children[child])
            if self.OnChild(child): self.active = child
        try:
            self.r_pos = tuple(self.pos[i]-self.children[self.active][i] for i in range(2))
            if self.r_pos[0] == -1: print(self.active)
        except KeyError:
            pass
        for event in pygame.event.get():
            if event.type == QUIT:
                self.qqq()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    self.qqq()
                if event.key == K_s:
                    self.save()
                if event.key == K_l:
                    self.load()
            if event.type == MOUSEBUTTONDOWN:
                try:
                    self.btn[event.button-1] = True
                except:
                    pass

    def OnChild(self,child):
        pos,size = self.children[child],child.size
        return(self.pos[0] in range(pos[0],pos[0]+size[0]) and
               self.pos[1] in range(pos[1],pos[1]+size[1]))

    def qqq(self):
        sys.exit()

    def save(self):
        f = open(self.name,'wb')
        outmap = dict((i,(str(self.map[i]),self.map[i].okToCross,self.map[i].portalTo)) for i in self.map)
        pickle.dump(0,f)
        pickle.dump(self.dim,f)
        pickle.dump(outmap,f)
        f.close()
        self.info_w.update('Saved as {}!'.format(self.name),2)
        self.screen.blit(self.info_w.screen,self.children[self.info_w])

    def load(self):
        f = open(self.name,'rb')
        n = pickle.load(f)
        s = pickle.load(f)
        m = pickle.load(f)
        f.close()
        for i in m:
            m[i] = Tile.Tile(Pic.Pic(m[i][0]),m[i][1],m[i][2])
        self.map = m  
        self.nx,self.ny = self.dim = s
        self.map_w = map_w(self) 
        self.children = {self.sys_w:(0,0),self.map_w:(self.split[0]+4,0),
                         self.name_w:(0,self.split[1]+4),self.info_w:(self.split[0]+4,self.split[1]+4)}
        for child in self.children:
            self.screen.blit(child.screen,self.children[child])
            if self.OnChild(child): self.active = child
        self.info_w.update('Loaded {}!'.format(self.name),2)
        self.screen.blit(self.info_w.screen,self.children[self.info_w])

    def loop(self):
        self.get_input()
        self.info_w.timer()
        self.clock.tick(60)
        out = ''
        try:
            out = self.active.loop()
            self.screen.blit(self.active.screen,self.children[self.active])
        except AttributeError as e:
            print(e)
            #raise Exception(e)
            pass
        #self.name_w.update(str(self.name)+': '+str(out))
        #self.screen.blit(self.name_w.screen,self.children[self.name_w])
        self.info_w.update(str(self.name)+': '+str(out),-1)
        self.screen.blit(self.info_w.screen,self.children[self.info_w])
        pygame.display.flip()
        return True
    
c = core()
while c.loop():
    pass
